<?php
/**
 * Author: lf
 * Blog: https://blog.szdma.com
 * Email: job@szdma.com
 * Created at: 2017-12-27 14:53.
 */

namespace common\helpers;

use yii\imagine\Image;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;

class Util
{
    /**
     * @Notes
     * @Interface handleModelSingleFileUpload
     *
     * @param ActiveRecord $model
     * @param $field
     * @param $insert
     * @param $uploadPath
     * @param array $options
     *
     * @return bool
     * @throws \yii\base\Exception
     * @Author Aaron/刘志勇
     * @Email lzymail@foxmail.com
     * @Date 2019-12-20 10:15
     */
    public static function handleModelSingleFileUpload(ActiveRecord &$model, $field, $insert, $uploadPath, $options = [])
    {
        $upload = UploadedFile::getInstance($model, $field);
//        /* @var $cdn \szdma\cdn\TargetInterface */
//        $cdn = yii::$app->get('cdn');
        if (null !== $upload) {
            $uploadPath = yii::getAlias($uploadPath);
            if (0 !== strpos(strrev($uploadPath), '/')) {
                $uploadPath .= '/';
            }
            if (!FileHelper::createDirectory($uploadPath)) {
                $model->addError($field, 'Create directory failed '.$uploadPath);

                return false;
            }
            $fullName = isset($options['filename']) ? $uploadPath.$options['filename'] : $uploadPath.date('YmdHis').'_'.uniqid().'.'.$upload->getExtension();
            if (!$upload->saveAs($fullName)) {
                $model->addError(
                    $field,
                    yii::t('app', 'Upload {attribute} error: '.$upload->error, ['attribute' => yii::t('app', ucfirst($field))]).': '.$fullName
                );

                return false;
            }
            $model->$field = str_replace(yii::getAlias('@pathRoot'), '', $fullName);
//            $cdn->upload($fullName, $model->$field);
            if (isset($options['thumbSizes'])) {
                self::thumbnails($fullName, $options['thumbSizes']);
            }
            if (!$insert) {
                $file = yii::getAlias('@pathRoot').$model->getOldAttribute($field);
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
//                if( $cdn->exists( $model->getOldAttribute($field) ) ) $cdn->delete($model->getOldAttribute($field));
                if (isset($options['thumbSizes']) && !empty($model->getOldAttribute($field))) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
            }
        } else {
            if ($model->$field === '0') {//删除
                $file = yii::getAlias('@pathRoot').$model->getOldAttribute($field);
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
//                if( $cdn->exists( $model->getOldAttribute($field) ) ) $cdn->delete($model->getOldAttribute($field));
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
                $model->$field = '';
            } else {
                if ($insert) {
                    $model->$field = !empty($model->$field) ? '' : $model->$field;
                } else {
                    $model->$field = $model->getOldAttribute($field);
                }
            }
        }
    }

    /**
     * 生成各个尺寸的缩略图.
     *
     * @param $fullName string 原图路径
     * @param array $thumbSizes 二维数组 如 [["w"=>110,"height"=>"20"],["w"=>200,"h"=>"30"]]则生成两张缩量图，分别为宽110高20和宽200高30
     */
    public static function thumbnails($fullName, array $thumbSizes)
    {
        foreach ($thumbSizes as $info) {
            $thumbFullName = self::getThumbName($fullName, $info['w'], $info['h']);
            Image::thumbnail($fullName, $info['w'], $info['h'])->save($thumbFullName);
//            /** @var $cdn \szdma\cdn\TargetInterface */
//            $cdn = yii::$app->get('cdn');
//            $cdn->upload($thumbFullName, str_replace(yii::getAlias('@pathRoot'), '', $thumbFullName));
        }
    }

    /**
     * 根据原图路径生成缩略图路径.
     *
     * @param $fullName string 原图路径
     * @param $width int 长
     * @param $heith int 宽
     *
     * @return string 如/path/to/uploads/article/xx@100x20.png
     */
    public static function getThumbName($fullName, $width, $heith)
    {
        $dotPosition = strrpos($fullName, '.');
        $thumbExt    = '@'.$width.'x'.$heith;
        if (false === $dotPosition) {
            $thumbFullName = $fullName.$thumbExt;
        } else {
            $thumbFullName = substr_replace($fullName, $thumbExt, $dotPosition, 0);
        }

        return $thumbFullName;
    }

    /**
     * 删除各个尺寸的缩略图.
     *
     * @param $fullName string 原图图片路径
     * @param $thumbSizes array 二维数组 如 [["w"=>110,"height"=>"20"],["w"=>200,"h"=>"30"]]则生成两张缩量图，分别为宽110高20和宽200高30
     */
    public static function deleteThumbnails($fullName, array $thumbSizes, $deleteOrigin = false)
    {
        foreach ($thumbSizes as $info) {
            $thumbFullName = self::getThumbName($fullName, $info['w'], $info['h']);
            if (file_exists($thumbFullName) && is_file($thumbFullName)) {
                unlink($thumbFullName);
            }
//            $cdn = yii::$app->get('cdn');
//            $cdn->delete(str_replace(yii::getAlias("@pathRoot"), '', $thumbFullName));
        }
        if ($deleteOrigin) {
            file_exists($fullName) && unlink($fullName);
        }
    }

    public static function handleModelSingleFileUploadAbnormal(ActiveRecord &$model, $field, $uploadPath, $oldFullname, $options = [])
    {
        if (!isset($options['successDeleteOld'])) {
            $options['successDeleteOld'] = true;
        } //成功后删除旧文件
        if (!isset($options['deleteOldFile'])) {
            $options['deleteOldFile'] = false;
        } //删除旧文件
        $upload = UploadedFile::getInstance($model, $field);
//        /* @var $cdn \szdma\cdn\TargetInterface */
//        $cdn = yii::$app->get('cdn');
        if (null !== $upload) {
            $uploadPath = yii::getAlias($uploadPath);
            if (0 !== strpos(strrev($uploadPath), '/')) {
                $uploadPath .= '/';
            }
            if (!FileHelper::createDirectory($uploadPath)) {
                $model->addError($field, 'Create directory failed '.$uploadPath);

                return false;
            }
            $fullName = isset($options['filename']) ? $uploadPath.$options['filename'] : $uploadPath.date('YmdHis').'_'.uniqid().'.'.$upload->getExtension();
            if (!$upload->saveAs($fullName)) {
                $model->addError(
                    $field,
                    yii::t('app', 'Upload {attribute} error: '.$upload->error, ['attribute' => yii::t('app', ucfirst($field))]).': '.$fullName
                );

                return false;
            }
            $model->$field = str_replace(yii::getAlias('@pathRoot'), '', $fullName);
//            $cdn->upload($fullName, $model->$field);
            if (isset($options['thumbSizes'])) {
                self::thumbnails($fullName, $options['thumbSizes']);
            }
            if ($options['successDeleteOld'] && $oldFullname) {
                $file = yii::getAlias('@pathRoot').$oldFullname;
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
//                if( $cdn->exists( $oldFullname ) ) $cdn->delete($oldFullname);
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
            }
        } else {
            if ($model->$field === '0') {//删除
                $file = yii::getAlias('@pathRoot').$oldFullname;
                if (file_exists($file) && is_file($file)) {
                    unlink($file);
                }
//                if( $cdn->exists( $oldFullname ) ) $cdn->delete($oldFullname);
                if (isset($options['thumbSizes'])) {
                    self::deleteThumbnails($file, $options['thumbSizes']);
                }
                $model->$field = '';
            } else {
                $model->$field = $oldFullname;
            }
        }
        if ($options['deleteOldFile']) {
            $file = yii::getAlias('@pathRoot').$oldFullname;
            if (file_exists($file) && is_file($file)) {
                unlink($file);
            }
//            if( $cdn->exists( $oldFullname ) ) $cdn->delete($oldFullname);
            if (isset($options['thumbSizes'])) {
                self::deleteThumbnails($file, $options['thumbSizes']);
            }
        }
    }
}
